package gui;

import export.BeanDefinition;
import export.Generator;
import gui.subpanel.ColumnControlTableCellHandler;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

public class GuiEventHandler {

	private static String previousSelectedDirectoryPath = null;

	/**
	 * On Created
	 * 
	 * @param main
	 *            Main
	 */
	protected static void onCreated(Main main) {
		// init table cell control panel
		JTable table = main.getTable_1();
		// seqNo cell
		DefaultTableCellRenderer columnSeqNoCellRenderer = new DefaultTableCellRenderer();
		columnSeqNoCellRenderer
				.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
		table.getColumnModel().getColumn(0)
				.setCellRenderer(columnSeqNoCellRenderer);
		// control cell
		TableColumn columnControlTableCell = table.getColumnModel()
				.getColumn(3);
		final ColumnControlTableCellHandler columnControlTableCellHandler = new ColumnControlTableCellHandler();
		columnControlTableCell.setCellRenderer(columnControlTableCellHandler
				.getTableCellRenderer());
		columnControlTableCell.setCellEditor(columnControlTableCellHandler
				.getTableCellEditor());
		// bind table cell control panel event
		final DefaultTableModel tableModel = ((DefaultTableModel) table
				.getModel());
		columnControlTableCellHandler
				.bindAddButtonActionListener(new ActionListener() {
					private int seqNo = 1;

					public void actionPerformed(ActionEvent e) {
						seqNo++;
						tableModel.addRow(new Object[] { String.valueOf(seqNo),
								"", "" });
					}
				});
		columnControlTableCellHandler
				.bindRemoveButtonActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						int currentRowIndex = columnControlTableCellHandler
								.getCurrentRowIndex();
						if (columnControlTableCellHandler.getPanelList().size() >= 2) {
							tableModel.removeRow(currentRowIndex);
							columnControlTableCellHandler.getPanelList()
									.remove(currentRowIndex);
						}
					}
				});
		columnControlTableCellHandler
				.bindUpButtonActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						int currentRowIndex = columnControlTableCellHandler
								.getCurrentRowIndex();
						if (currentRowIndex >= 1) {
							tableModel.moveRow(currentRowIndex,
									currentRowIndex, currentRowIndex - 1);
						}
					}
				});
		columnControlTableCellHandler
				.bindDownButtonActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						int currentRowIndex = columnControlTableCellHandler
								.getCurrentRowIndex();
						if (currentRowIndex < columnControlTableCellHandler
								.getPanelList().size() - 1) {
							tableModel.moveRow(currentRowIndex,
									currentRowIndex, currentRowIndex + 1);
						}
					}
				});
	}

	/**
	 * On Cancel Button Click
	 * 
	 * @param frame
	 *            JFrame
	 */
	protected static void onCancelButtonClick(JFrame frame) {
		frame.dispose();
		System.exit(0);
	}

	/**
	 * On Generate Button Click
	 * 
	 * @param main
	 *            Main
	 */
	protected static void onGenerateButtonClick(Main main) {
		// file chooser
		JFileChooser fc = new JFileChooser();
		fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		fc.setAcceptAllFileFilterUsed(false);
		fc.addChoosableFileFilter(new FileFilter() {
			@Override
			public String getDescription() {
				return "Directory";
			}

			@Override
			public boolean accept(File arg0) {
				return arg0.isDirectory();
			}
		});
		if (previousSelectedDirectoryPath != null) {
			fc.setCurrentDirectory(new File(previousSelectedDirectoryPath));
		}
		// export
		try {
			String className = main.getTextField_1().getText().trim();
			String packageName = main.getTextField().getText().trim();
			if (className.length() <= 0) {
				throw new IllegalArgumentException("Class name undefined");
			}
			if (fc.showSaveDialog(main.getFrame()) == JFileChooser.APPROVE_OPTION) {
				String exportPath = fc.getSelectedFile().getPath();
				// column names
				DefaultTableModel tableModel = ((DefaultTableModel) main
						.getTable_1().getModel());
				List<BeanDefinition> beanDefinitionList = new ArrayList<BeanDefinition>();
				for (int i = 0, rowCount = tableModel.getRowCount(); i < rowCount; i++) {
					beanDefinitionList.add(new BeanDefinition(
							(String) tableModel.getValueAt(i, 1),
							(String) tableModel.getValueAt(i, 2)));
				}
				Generator factory = new Generator(className, packageName,
						exportPath);
				if (!factory.isAnyOutputFileExisted()) {
					factory.generateGlobalSettingFile(false);
					factory.generateSqlDefinitionFile(beanDefinitionList, false);
					factory.generateBeanDefinitionFile(beanDefinitionList,
							false);
					factory.generateDaoDefinitionFile(false);
					// done message
					JOptionPane.showMessageDialog(main.getFrame(), "Done");
				} else if (JOptionPane.showConfirmDialog(main.getFrame(),
						"Would you like to overwrite existed files?",
						"Warning", JOptionPane.YES_NO_OPTION,
						JOptionPane.WARNING_MESSAGE) == JOptionPane.YES_OPTION) {
					factory.generateGlobalSettingFile(true);
					factory.generateSqlDefinitionFile(beanDefinitionList, true);
					factory.generateBeanDefinitionFile(beanDefinitionList, true);
					factory.generateDaoDefinitionFile(true);
					// done message
					JOptionPane.showMessageDialog(main.getFrame(), "Done");
				}
				previousSelectedDirectoryPath = exportPath;
			} else {
				previousSelectedDirectoryPath = fc.getCurrentDirectory()
						.getPath();
			}
		} catch (Throwable e) {
			JOptionPane.showMessageDialog(main.getFrame(), e.getMessage(),
					"Error", JOptionPane.ERROR_MESSAGE);
			e.printStackTrace();
		}
	}

}